package cn.bm.web.services;

import cn.bm.web.db.DBConfig;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UserServices {

    private static final Logger logger = LoggerFactory.getLogger(UserServices.class);

    // 原有的登录方法
    public static boolean login(String username, String password) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet resultSet = null;
        try {
            conn = DBConfig.getConnection();
            pstmt = conn.prepareStatement("SELECT * FROM nginx WHERE username =? AND password =?");
            pstmt.setString(1, username);
            String hashedPassword = DigestUtils.md5Hex(password);
            logger.debug("Login query with username: {}, hashed password: {}", username, hashedPassword);
            pstmt.setString(2, hashedPassword);
            resultSet = pstmt.executeQuery();
            return resultSet.next();
        } catch (SQLException ex) {
            logger.error(ex.getMessage());
            return false;
        } finally {
            try {
                if (resultSet!= null) resultSet.close();
                if (pstmt!= null) pstmt.close();
                if (conn!= null) conn.close();
            } catch (SQLException ex) {
                logger.error(ex.getMessage());
            }
        }
    }

    // 新增的注册方法
    public static boolean register(String username, String password) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = DBConfig.getConnection();
            // 检查用户名是否已存在
            PreparedStatement checkStmt = conn.prepareStatement("SELECT * FROM nginx WHERE username =?");
            checkStmt.setString(1, username);
            ResultSet checkResultSet = checkStmt.executeQuery();
            if (checkResultSet.next()) {
                logger.error("Username {} already exists.", username);
                return false;
            }
            pstmt = conn.prepareStatement("INSERT INTO nginx (username, password) VALUES (?,?)");
            pstmt.setString(1, username);
            String hashedPassword = DigestUtils.md5Hex(password);
            logger.debug("Registration with username: {}, hashed password: {}", username, hashedPassword);
            pstmt.setString(2, hashedPassword);
            int rowsAffected = pstmt.executeUpdate();
            return rowsAffected > 0;
        } catch (SQLException ex) {
            logger.error(ex.getMessage());
            return false;
        } finally {
            try {
                if (pstmt!= null) pstmt.close();
                if (conn!= null) conn.close();
            } catch (SQLException ex) {
                logger.error(ex.getMessage());
            }
        }
    }
}